#include "form_jcmlxz.h"
#include "ui_form_jcmlxz.h"

#include "pub_var.h"
#include "QPushButton"
#include <QDebug>
#include <QDate>
#include <QMessageBox>
#include <QRegExp>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QTimer>
#include <QFile>
//#include <QTextCodec>
#include <QFileDialog>
#include "zip/JlCompress.h"

//extern QString curBusiness;
QString curBusiness;

Form_jcmlxz::Form_jcmlxz(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_jcmlxz)
{
    ui->setupUi(this);

    //恢复当前窗口位置
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/jcmlxz").toRect();
    this->setGeometry(rct);

    //数据库连接
    qro = new QSqlQuery(pub::db_o);
    qrm = new QSqlQuery(pub::db_m);

    //状态显示
    ui->dtStart->setDate(QDate::currentDate());

    //可供使用的交易代码
    qrm->exec("select code,name from new_downs where valid_flag = '1'");
    ui->cbbList->clear();
    QString itm;
    while(qrm->next()){
        itm = qrm->value(0).toString().trimmed() ;
        itm.append(" ");
        itm.append(qrm->value(1).toString().trimmed());
        ui->cbbList->addItem(itm);
    }

    //定时器，控制窗口状态栏显示
    tm = new QTimer(this);
    connect(tm, SIGNAL(timeout()), this, SLOT(onTimeOut()));
    tm0 = new QTimer(this);
    connect(tm0, SIGNAL(timeout()), this, SLOT(onTime0Out()));

    //网络参数
    request.setUrl(QUrl(pub::hos_ybjy));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    //zip动态库存是否存在
    QString zipFile = QCoreApplication::applicationDirPath() + "/quazip.dll";
    QFile f;
    if(f.exists(zipFile) ){
        hasZip = true;
        ui->ckbAutoUnzip->setEnabled(true);
        ui->ckbAutoUnzip->setChecked(true);
    } else {
        hasZip = false;
        ui->ckbAutoUnzip->setEnabled(false);
        ui->ckbAutoUnzip->setChecked(false);
    }
}

Form_jcmlxz::~Form_jcmlxz()
{
    delete ui;
}

void Form_jcmlxz::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/jcmlxz", QVariant(this->geometry()));
}


void Form_jcmlxz::onTimeOut()
{

    //控制状态栏文本闪动显示，当前状态为空则显示状态，状态非空则清空
    if(ui->leStatus->text().isEmpty()){
        ui->leStatus->setText( curStatus + QString::number(nowrows) + "/" + QString::number(endrows));
    }else{
        ui->leStatus->setText("");
    }
    qApp->processEvents();  //刷新显示
}

void Form_jcmlxz::on_pbExit_clicked()
{

    this->close();

}

bool Form_jcmlxz::importData(QString fileName)
{
    //交易代码
    QString jydm = pub::getStr(ui->cbbList->currentText()," ",1);

    if (!fileName.isNull()){

        //文本文件格式是否为 utf8
        if(ui->rbUtf8->isChecked()){
            qrm->exec("set names utf8");
        }
        sq = " LOAD DATA local INFILE '" + fileName + "' replace INTO TABLE new_down_" + jydm;
        if(!qrm->exec(sq)){
            qDebug()<<qrm->lastError().text();
            qDebug()<<qrm->lastQuery();
            QMessageBox::information(this,"注意", " 导入数据失败: " + qrm->lastError().text());
        }else{
            QMessageBox::information(this,"注意", " 数据导入成功！");
            //1,3,5,6 版本名称
            //7,8 版本号
            QString v;
            //如果导入成功，jydm 必定有效，所以不需要多做判断

            if(jydm == "1307" || jydm == "1308"){
                v = "版本号";
            }else{
                v = "版本名称";
            }
            curStatus = "查询导入的最新版本。。。";
            qApp->processEvents();  //刷新显示
            //查询导入的最新版本
            sq = "SELECT distinct " + v + " FROM clinic.new_down_" + jydm + " where " + v + " not in "
                 "(select version from com_download_version where jydm = '" + jydm + "')";
            qDebug() << "查询导入的最新版本 sql : " << sq;
            qrm->exec(sq);
            if(qrm->next()){    //查到最新版本号
                v = qrm->value(0).toString().trimmed();
                qDebug() << " 查询到的最新版本 : " << v;
                ui->lwResult->addItem( "最新版本号为： " + v );
                if(!qrm->exec("insert into com_download_version (version, jydm, datetime) "
                              " values('" + v + "','" + jydm + "',now())")){
                    QMessageBox::information(this,"注意", " 保存最新版本号失败！");
                    qDebug()<<qrm->lastQuery();
                }
            }else{
                QMessageBox::information(this,"注意", " 未能查询到有效的最新版本号，请手工指定！");
            }
        }
    }else{
        return false;
    }
    return true;

}
void Form_jcmlxz::on_pbImport_clicked()
{
    curStatus = "正在导入数据。。。";

    //控制状态栏文本显示

    //如定时器已经在工作，不需要再次启动
    bool impTimer = false;  //定时器在本模块启动，设置值为true
    if(!tm->isActive()){
        impTimer = true;
        ui->pbExit->setEnabled(false);
        ui->pbQuery->setEnabled(false);
        ui->pbImport->setEnabled(false);
        ui->pbDownload->setEnabled(false);
        tm->start(390);
    }
    //下载之后已经解压的文本文件
    QString fileName = QFileDialog::getOpenFileName(this, "打开可导入的文本文件",  "d:/0down/",  "(*.txt)",  0);

    importData(fileName);

    if(impTimer){
        tm->stop();
        ui->pbExit->setEnabled(true);
        ui->pbQuery->setEnabled(true);
        ui->pbImport->setEnabled(true);
        ui->pbDownload->setEnabled(true);

    }
    curStatus = "数据导入结束。";
    ui->leStatus->setText(curStatus);

}

void Form_jcmlxz::on_pbDownload_clicked()
{
    endrows = 0;
    nowrows = 0;

    //从列表中提取交易代码
    QString jydm = pub::getStr(ui->cbbList->currentText()," ",1);

    //检索本交易最后一次记录的版本号
    sq = "select version, datetime from com_download_version where jydm = '" + jydm + "' order by datetime desc";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"注意", " com_download_version 提取数据失败！");
        qDebug()<<qrm->lastQuery();
        return;
    }
    if(!qrm->next()){
        QMessageBox::information(this,"注意", " com_download_version 无数据！");
        return;
    }

    //
    ui->pbExit->setEnabled(false);
    ui->pbQuery->setEnabled(false);
    ui->pbImport->setEnabled(false);
    ui->pbDownload->setEnabled(false);

    tm->start(390);

    if(ui->cbVersion->isChecked()){
        ver = ui->leCondition->text();
    }else{
        ver = qrm->value(0).toString();
    }

    lastOperDate = qrm->value(1).toDate().toString("yyyy-MM-dd") + " 00:00:00";

    qDebug() << "lastOperDate is : " << lastOperDate;

    if( jydm == "1316" || jydm == "1318"){
        QMessageBox::information(this,"注意", "1316、1318 无需下载。");

    }else if( jydm == "1312" || jydm == "1317"){
        pageSize = ui->cbbPageItems->currentText().toInt();   //每页行数
        pages = 1;  //页数
        lastPage = false;  //是否最后一页
        if(ui->rbSpecial->isChecked()){
            startDate = ui->dtStart->date().toString("yyyy-MM-dd") + " 00:00:00";
        }else{
            startDate = lastOperDate;
        }
        while(!lastPage){
            if(!download(jydm)){//执行失败，退出
                break;
            }

            pages ++;
            qDebug()<<"current page :"<<pages;
        }
        //保存最后下载日期。文本文件下载的版本号在导入时更新
        if( lastPage){//执行成功
            if( jydm == "1312" || jydm == "1316" || jydm == "1317" || jydm == "1318"){
                if(!qrm->exec("insert into com_download_version (version, jydm, datetime) "
                              " values( '0','" + jydm + "',now())")){
                    QMessageBox::information(this,"注意", " 保存 com_download_version 失败！");
                    qDebug()<<qrm->lastQuery();
                }
            }
        }
    }else{
        if(!download(jydm)){
            businessSuccess = false;
        }
    }

    tm->stop();
    ui->leStatus->setText("操作完成");
    ui->pbExit->setEnabled(true);
    ui->pbQuery->setEnabled(true);
    ui->pbImport->setEnabled(true);
    ui->pbDownload->setEnabled(true);
}

bool Form_jcmlxz::download(QString jydm)
{

    //ui->leStatus->setText("开始执行医保交易。。。");

    qDebug() << "startDate is : " << startDate;
    curStatus = "开始执行 " + jydm + " 交易。。。";

    QJsonObject in;

    if(!putBaseIn(in, jydm)){
        return false;
    }

    QJsonObject inpu,inpud;

    if(jydm == "1301" || jydm == "1303" || jydm == "1305"
            || jydm == "1306" || jydm == "1307" ){
        inpu.insert("ver", ver);   //本地最大版本号
    }else if( jydm == "1312" || jydm == "1316" || jydm == "1317" || jydm == "1318"){
        inpu.insert("fixmedins_code",pub::hos_ybbh);
        inpu.insert("insu_admdvs",pub::hos_insuplc);
        inpu.insert("updt_time", startDate);   //更新时间
        inpu.insert("page_num", pages);    //当前页数
        inpu.insert("page_size", pageSize);   //本页数据量
    }else if( jydm == "1901"){
        inpu.insert("type", "");
        inpu.insert("admdvs", pub::hos_insuplc);
        inpu.insert("date", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
        inpu.insert("vali_flag", "1");
    }

    inpud.insert("data",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);

    qDebug()<<jydm +" 交易入参: "<<indoc;

    //保存入参日志
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    QNetworkReply* reply = manager.post(request,indoc.toJson());

    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意", jydm + " http 请求状态错误: " + statusCode.toString());
        return false;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",jydm + " : " + reply->errorString());
        return false;
    }

    QByteArray bt = reply->readAll();

    QString t = QString::fromLocal8Bit(bt);

    QJsonParseError json_error;
    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());
        return false;
    }

    QJsonObject jsob = jsdc.object();

    if(jsob.value("infcode").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意", jydm + " 交易失败：" + t );
        return false;
    }

    if(jydm == "1301" || jydm == "1303" || jydm == "1305"
            || jydm == "1306" || jydm == "1307" ){

        sq = "update com_business set v_out = '"
                + jsdc.toJson(QJsonDocument::Compact)
                + "' where jyls = '" + currentMsgid + "'";

        if(!qrm->exec(sq)){
            QMessageBox::information(this,"错误","保存 " + jydm + " 出参日志失败！");
            qDebug()<<sq;
        }
        QString file_qury_no = jsob.value("output").toObject().value("file_qury_no").toString();

        if(!saveFile(file_qury_no, jydm)){
            return false;
        }else{
            return true;
        }
    }

    retObj = jsob.value("output").toObject();

    endrows = retObj.value("endRow").toDouble();
    nowrows = retObj.value("recordCounts").toDouble();


    if( jydm == "1312" ){
        if(jsob.value("output").toObject().isEmpty()){
            QMessageBox::warning(NULL,"注意", jydm + "返回信息为空 ");
            lastPage = true;
            return true;
        }
        lastPage = jsob.value("output").toObject().value("lastPage").toBool();
        int recCount = jsob.value("output").toObject().value("size").toInt();
        QJsonArray retData = jsob.value("output").toObject().value("data").toArray();
        while(recCount > 0){
            recCount--;
            QJsonObject ob = retData[recCount].toObject();


            QString eddt = "2399-12-31 23:59:59";
            if(!ob.value("enddate").toString().isEmpty()){
                eddt = ob.value("enddate").toString("yyyy-MM-dd HH:mm:ss");
            }

            sq = "insert into new_down_1312 (hilist_code, hilist_name, insu_admdvs, begndate, enddate, "
                 "med_chrgitm_type, chrgitm_lv, lmt_used_flag, list_type, med_use_flag, matn_used_flag, "
                 "hilist_use_type, lmt_cpnd_type, wubi, pinyin, memo, vali_flag, rid, updt_time, crter_id, "
                 "crter_name, crte_time, crte_optins_no, opter_id, opter_name, opt_time, optins_no, poolarea_no)"
                 " values"
                 "('"+ob.value("hilist_code").toString()
                    + "', '" + removeSpecialChar(ob.value("hilist_name").toString())
                    + "', '" + ob.value("insu_admdvs").toString()
                    + "', '" + ob.value("begndate").toString("yyyy-MM-dd HH:mm:ss")
                    + "', '" + eddt
                    + "', '" + ob.value("med_chrgitm_type").toString()
                    + "', '" + ob.value("chrgitm_lv").toString()
                    + "', '" + ob.value("lmt_used_flag").toString()
                    + "', '" + ob.value("list_type").toString()
                    + "', '" + ob.value("med_use_flag").toString()
                    + "', '" + ob.value("matn_used_flag").toString()
                    + "', '" + ob.value("hilist_use_type").toString()
                    + "', '" + ob.value("lmt_cpnd_type").toString()
                    + "', '" + removeSpecialChar(ob.value("wubi").toString())
                    + "', '" + removeSpecialChar(ob.value("pinyin").toString())
                    + "', '" + removeSpecialChar(ob.value("memo").toString())
                    + "', '" + ob.value("vali_flag").toString()
                    + "', '" + ob.value("rid").toString()
                    + "', '" + ob.value("updt_time").toString("yyyy-MM-dd HH:mm:ss")
                    + "', '" + ob.value("crter_id").toString()
                    + "', '" + ob.value("crter_name").toString()
                    + "', '" + ob.value("crte_time").toString("yyyy-MM-dd HH:mm:ss")
                    + "', '" + ob.value("crte_optins_no").toString()
                    + "', '" + ob.value("opter_id").toString()
                    + "', '" + ob.value("opter_name").toString()
                    + "', '" + ob.value("opt_time").toString("yyyy-MM-dd HH:mm:ss")
                    + "', '" + ob.value("optins_no").toString()
                    + "', '" + ob.value("poolarea_no").toString()
                    +"') "
                    + " on duplicate key update "
                    + " insu_admdvs = '" + ob.value("insu_admdvs").toString()
                    + "', begndate = '" + ob.value("begndate").toString("yyyy-MM-dd HH:mm:ss")
                    + "', enddate = '" + eddt
                    + "', med_chrgitm_type = '"+ob.value("med_chrgitm_type").toString()
                    + "', chrgitm_lv = '"+ob.value("chrgitm_lv").toString()
                    + "', lmt_used_flag = '"+ob.value("lmt_used_flag").toString()
                    + "', list_type = '"+ob.value("list_type").toString()
                    + "', med_use_flag = '"+ob.value("med_use_flag").toString()
                    + "', matn_used_flag = '"+ob.value("matn_used_flag").toString()
                    + "', hilist_use_type = '"+ob.value("hilist_use_type").toString()
                    + "', lmt_cpnd_type = '"+ob.value("lmt_cpnd_type").toString()
                    + "', memo = '"+removeSpecialChar(ob.value("memo").toString())
                    + "', vali_flag = '"+ob.value("vali_flag").toString()
                    + "', rid = '"+ob.value("rid").toString()
                    + "', updt_time = '"+ob.value("updt_time").toString("yyyy-MM-dd HH:mm:ss")
                    + "', crter_id = '"+ob.value("crter_id").toString()
                    + "', crter_name = '"+ob.value("crter_name").toString()
                    + "', crte_time = '"+ob.value("crte_time").toString("yyyy-MM-dd HH:mm:ss")
                    + "', crte_optins_no = '"+ob.value("crte_optins_no").toString()
                    + "', opter_id = '"+ob.value("opter_id").toString()
                    + "', opter_name = '"+ob.value("opter_name").toString()
                    + "', opt_time = '"+ob.value("opt_time").toString("yyyy-MM-dd HH:mm:ss")
                    + "', optins_no = '"+ob.value("optins_no").toString()
                    + "', poolarea_no = '"+ob.value("poolarea_no").toString()
                    + "'"
                    ;

            if(!qrm->exec(sq)){

                qDebug()<<"sql error: " << qrm->lastError().text();
                qDebug()<< "sql : " << sq;
                QMessageBox::warning(this, "注意","数据表 new_down_1312 插入错误！");
                lastPage = true;
                return false;
            }

        }

    }else if(jydm == "1316"){
        //医疗目录与医保目录匹配信息
        if(jsob.value("output").toObject().isEmpty()){
            QMessageBox::warning(NULL,"注意", jydm + "返回信息为空 ");
            lastPage = true;
            return true;
        }

        lastPage = jsob.value("output").toObject().value("lastPage").toBool();
        int recCount = jsob.value("output").toObject().value("size").toInt();
        QJsonArray retData = jsob.value("output").toObject().value("data").toArray();
        while(recCount > 0){
            recCount--;
            QJsonObject ob = retData[recCount].toObject();

            QString eddt = "2399-12-31 23:59:59";
            if(!ob.value("enddate").toString().isEmpty()){
                eddt = ob.value("enddate").toString("yyyy-MM-dd HH:mm:ss");
            }

            qrm->prepare("insert into new_down_1316 "
                         " (med_list_codg, hilist_code, list_type, insu_admdvs, begndate, enddate, memo, "
                         " vali_flag, rid, updt_time, crter_id, crter_name, crte_time, crte_optins_no, opter_id,"
                         " opter_name, opt_time, optins_no, poolarea_no)"
                         " values "
                         "('"+ob.value("med_list_codg").toString()
                         + "', '" + ob.value("hilist_code").toString()
                         + "', '" + ob.value("list_type").toString()
                         + "', '" + ob.value("insu_admdvs").toString()
                         + "', '" + ob.value("begndate").toString("yyyy-MM-dd HH:mm:ss")
                         + "', '" + eddt
                         + "', '" + removeSpecialChar(ob.value("memo").toString())
                         + "', '" + ob.value("vali_flag").toString()
                         + "', '" + ob.value("rid").toString()
                         + "', '" + ob.value("updt_time").toString()
                         + "', '" + ob.value("crter_id").toString()
                         + "', '" + ob.value("crter_name").toString()
                         + "', '" + ob.value("crte_time").toString("yyyy-MM-dd HH:mm:ss")
                         + "', '" + ob.value("crte_optins_no").toString()
                         + "', '" + ob.value("opter_id").toString()
                         + "', '" + ob.value("opter_name").toString()
                         + "', '" + ob.value("begndate").toString("yyyy-MM-dd HH:mm:ss")
                         + "', '" + ob.value("optins_no").toString()
                         + "', '" + ob.value("poolarea_no").toString()
                         + "') "
                         + " on duplicate key update "
                         + " med_list_codg = '" + ob.value("med_list_codg").toString()
//                         + "', hilist_code = '" + ob.value("hilist_code").toString()
                         + "', list_type = '" + ob.value("list_type").toString()
                         + "', insu_admdvs = '" + ob.value("insu_admdvs").toString()
                         + "', begndate = '" + ob.value("begndate").toString("yyyy-MM-dd HH:mm:ss")
                         + "', enddate = '" + eddt
                         + "', memo = '" + removeSpecialChar(ob.value("memo").toString())
                         + "', vali_flag = '" + ob.value("vali_flag").toString()
                         + "', rid = '" + ob.value("rid").toString()
                         + "', updt_time = '" + ob.value("updt_time").toString()
                         + "', crter_id = '" + ob.value("crter_id").toString()
                         + "', crter_name = '" + ob.value("crter_name").toString()
                         + "', crte_time = '" + ob.value("crte_time").toString("yyyy-MM-dd HH:mm:ss")
                         + "', crte_optins_no = '" + ob.value("crte_optins_no").toString()
                         + "', opter_id = '" + ob.value("opter_id").toString()
                         + "', opter_name = '" + ob.value("opter_name").toString()
                         + "', begndate = '" + ob.value("begndate").toString("yyyy-MM-dd HH:mm:ss")
                         + "', optins_no = '" + ob.value("optins_no").toString()
                         + "', poolarea_no = '" + ob.value("poolarea_no").toString()
                         );

            if(!qrm->exec()){
                qDebug()<<qrm->lastError().text();
                qDebug()<<qrm->lastQuery();
                QMessageBox::warning(this, "注意","数据表 new_down_1316 插入错误！");
                lastPage = true;
                return false;
            }

        }
    }else if(jydm == "1317"){
        //医药机构目录匹配信息查询
        //对照上传过的项目，可以通过本交易查询下载。
        qDebug()<<"value of 1317";
        if(jsob.value("output").toObject().isEmpty()){
            lastPage = true;
            QMessageBox::warning(NULL,"注意", jydm + "返回信息为空 ");
            return false;
        }
        lastPage = jsob.value("output").toObject().value("lastPage").toBool();
        int recCount = jsob.value("output").toObject().value("size").toInt();

        QJsonArray retData = jsob.value("output").toObject().value("data").toArray();
        while(recCount > 0){
            recCount--;
            QJsonObject ob = retData[recCount].toObject();
            QString eddt = "2399-12-31 23:59:59";
            if(!ob.value("enddate").toString().isEmpty()){
                eddt = ob.value("enddate").toString("yyyy-MM-dd HH:mm:ss");
            }

            qrm->prepare("insert into new_down_1317 "
                         "(fixmedins_code, medins_list_codg, medins_list_name, insu_admdvs, "
                         " list_type, med_list_codg, begndate, enddate, aprvno, dosform, exct_cont,"
                         " item_cont, prcunt, spec, pacspec, memo, vali_flag, rid, updt_time, crter_id,"
                         " crter_name, crte_time, crte_optins_no, opter_id, opter_name, opt_time,"
                         " optins_no, poolarea_no )"
                         " values "
                         " ('" + ob.value("fixmedins_code").toString()
                         + "','" + ob.value("medins_list_codg").toString()
                         + "' , '" + removeSpecialChar(ob.value("medins_list_name").toString())
                         + "','" + ob.value("insu_admdvs").toString()
                         + "', '" + ob.value("list_type").toString()
                         + "', '" + ob.value("med_list_codg").toString()
                         + "', '" + ob.value("begndate").toString("yyyy-MM-dd HH:mm:ss")
                         + "', '" + eddt
                         + "','" + ob.value("aprvno").toString()
                         + "','" + ob.value("dosform").toString()
                         + "','" + ob.value("exct_cont").toString()
                         + "', '" + ob.value("item_cont").toString()
                         + "', '" + ob.value("prcunt").toString()
                         + "', '" + ob.value("spec").toString()
                         + "', '" + ob.value("pacspec").toString()
                         + "', '" + removeSpecialChar(ob.value("memo").toString())
                         + "', '" + ob.value("vali_flag").toString()
                         + "','" + ob.value("rid").toString()
                         + "', '" + ob.value("updt_time").toString("yyyy-MM-dd HH:mm:ss")
                         + "', '" + ob.value("crter_id").toString()
                         + "', '" + ob.value("crter_name").toString()
                         + "', '" + ob.value("crte_time").toString("yyyy-MM-dd HH:mm:ss")
                         + "', '" + ob.value("crte_optins_no").toString()
                         + "','" + ob.value("opter_id").toString()
                         + "', '" + ob.value("opter_name").toString()
                         + "', '" + ob.value("opt_time").toString("yyyy-MM-dd HH:mm:ss")
                         + "', '" + ob.value("optins_no").toString()
                         + "', '" + ob.value("poolarea_no").toString()+ "' )"
                         + " on duplicate key update "
                         + " fixmedins_code = '" + ob.value("fixmedins_code").toString()
//                         //+ "', medins_list_codg = '" + ob.value("medins_list_codg").toString()
                         + "', medins_list_name = '" + removeSpecialChar(ob.value("medins_list_name").toString())
                         + "', insu_admdvs = '" + ob.value("insu_admdvs").toString()
                         + "', list_type = '" + ob.value("list_type").toString()
                         + "', med_list_codg = '" + ob.value("med_list_codg").toString()
                         + "', begndate = '" + ob.value("begndate").toString("yyyy-MM-dd HH:mm:ss")
                         + "', enddate = '" + eddt
                         + "', aprvno = '" + ob.value("aprvno").toString()
                         + "', dosform = '" + ob.value("dosform").toString()
                         + "', exct_cont = '" + ob.value("exct_cont").toString()
                         + "', item_cont = '" + ob.value("item_cont").toString()
                         + "', prcunt = '" + ob.value("prcunt").toString()
                         + "', spec = '" + ob.value("spec").toString()
                         + "', pacspec = '" + ob.value("pacspec").toString()
                         + "', memo = '" + removeSpecialChar(ob.value("memo").toString())
                         + "', vali_flag = '" + ob.value("vali_flag").toString()
                         + "', rid = '" + ob.value("rid").toString()
                         + "', updt_time = '" + ob.value("updt_time").toString("yyyy-MM-dd HH:mm:ss")
                         + "', crter_id = '" + ob.value("crter_id").toString()
                         + "', crter_name = '" + ob.value("crter_name").toString()
                         + "', crte_time = '" + ob.value("crte_time").toString("yyyy-MM-dd HH:mm:ss")
                         + "', crte_optins_no = '" + ob.value("crte_optins_no").toString()
                         + "', opter_id = '" + ob.value("opter_id").toString()
                         + "', opter_name = '" + ob.value("opter_name").toString()
                         + "', opt_time = '" + ob.value("opt_time").toString("yyyy-MM-dd HH:mm:ss")
                         + "', optins_no = '" + ob.value("optins_no").toString()
                         + "', poolarea_no = '" + ob.value("poolarea_no").toString()+ "' "

                         );

            if(!qrm->exec()){
                qDebug()<<qrm->lastError().text();
                qDebug()<<qrm->lastQuery();
                QMessageBox::warning(this, "注意","数据表 new_down_1317 插入错误！");
                lastPage = true;
                return false;
            }
        }
    }else if(jydm == "1318"){
        if(jsob.value("output").toObject().isEmpty()){
            lastPage = true;
            QMessageBox::warning(NULL,"注意", jydm + "返回信息为空 ");
            return true;
        }
        int recCount = jsob.value("output").toObject().value("size").toInt();

        if(recCount == 0){
            lastPage = true;
            QMessageBox::warning(NULL,"注意", jydm + " 查询无结果 ");
            return true;
        }

        lastPage = jsob.value("output").toObject().value("lastPage").toBool();
        QJsonArray retData = jsob.value("output").toObject().value("data").toArray();
        while(recCount > 0){
            recCount--;
            QJsonObject ob = retData[recCount].toObject();

            QString eddt = "2399-12-31 23:59:59";
            if(!ob.value("enddate").toString().isEmpty()){
                eddt = ob.value("enddate").toString("yyyy-MM-dd HH:mm:ss");
            }


            qrm->prepare("insert into new_down_1318 "
                         "(hilist_code,hilist_lmtpric_type,overlmt_dspo_way,insu_admdvs,begndate,enddate,"
                         " hilist_pric_uplmt_amt,vali_flag,rid,updt_time,crter_id,crter_name,crte_time,"
                         " crte_optins_no,opter_id,opter_name,opt_time,optins_no,tabname,poolarea_no)"
                         " values "
                         "(:hilist_code,:hilist_lmtpric_type,:overlmt_dspo_way,:insu_admdvs,:begndate,:enddate,"
                         " :hilist_pric_uplmt_amt,:vali_flag,:rid,:updt_time,:crter_id,:crter_name,:crte_time,"
                         " :crte_optins_no,:opter_id,:opter_name,:opt_time,:optins_no,:tabname,:poolarea_no)"
                         );
            qrm->bindValue(":hilist_code", ob.value("hilist_code").toString());
            qrm->bindValue(":hilist_lmtpric_type", ob.value("hilist_lmtpric_type").toString());
            qrm->bindValue(":overlmt_dspo_way", ob.value("overlmt_dspo_way").toString());
            qrm->bindValue(":insu_admdvs", ob.value("insu_admdvs").toString());
            qrm->bindValue(":begndate", QDateTime::fromString(ob.value("begndate").toString(),"yyyy-MM-dd HH:mm:ss"));
            if(!ob.value("enddate").toString().isEmpty()){
                qrm->bindValue(":enddate", QDateTime::fromString(ob.value("enddate").toString(),"yyyy-MM-dd HH:mm:ss"));
            }
            qrm->bindValue(":hilist_pric_uplmt_amt", ob.value("hilist_pric_uplmt_amt").toDouble());
            qrm->bindValue(":vali_flag", ob.value("vali_flag").toString());
            qrm->bindValue(":rid", ob.value("rid").toString());
            qrm->bindValue(":updt_time", QDateTime::fromString(ob.value("updt_time").toString(),"yyyy-MM-dd HH:mm:ss"));
            qrm->bindValue(":crter_id", ob.value("crter_id").toString());
            qrm->bindValue(":crter_name", ob.value("crter_name").toString());
            qrm->bindValue(":crte_time", QDateTime::fromString(ob.value("crte_time").toString(),"yyyy-MM-dd HH:mm:ss"));
            qrm->bindValue(":crte_optins_no", ob.value("crte_optins_no").toString());
            qrm->bindValue(":opter_id", ob.value("opter_id").toString());
            qrm->bindValue(":opter_name", ob.value("opter_name").toString());
            if(!ob.value("opt_time").toString().isEmpty()){
                qrm->bindValue(":opt_time", QDateTime::fromString(ob.value("opt_time").toString(),"yyyy-MM-dd HH:mm:ss"));
            }
            qrm->bindValue(":optins_no", ob.value("optins_no").toString());
            qrm->bindValue(":tabname", ob.value("tabname").toString());
            qrm->bindValue(":poolarea_no", ob.value("poolarea_no").toString());
            if(!qrm->exec()){
                qDebug()<<qrm->lastError().text();
                QMessageBox::warning(this, "注意","数据表 new_down_1318 插入错误！");
                lastPage = true;
                return false;
            }
        }
    }else if(jydm == "1901"){

        if(jsob.value("output").toObject().isEmpty()){
            lastPage = true;
            QMessageBox::warning(NULL,"注意", jydm + "返回信息为空 ");
            return true;
        }
        qrm->exec("delete from com_dict_new");
        QJsonArray retData = jsob.value("output").toObject().value("list").toArray();
        QJsonArray::iterator st = retData.begin();
        QJsonArray::iterator ed = retData.end();
        QString dt;
        while( st != ed){
            QJsonObject ob = st->toObject();
//            dt = ob.value("create_date").toString().isEmpty();
//            if(dt.isEmpty()){
//                dt = "0000-00-00 00:00:00";
//            }
            //create_user,create_date,

            sq = "insert into com_dict_new"
                 " (dic_type,dic_label,dic_value,parent_value,sort,"
                 "vali_flag,version)"
                 "values ('"
                    + ob.value("type").toString()
                    + "','" + ob.value("label").toString()
                    + "','" + ob.value("value").toString()
                    + "','" + ob.value("parent_value").toString()
                    + "'," + QString::number(ob.value("sort").toDouble())
                    + ",'" + ob.value("vali_flag").toString()
            //        + "','" + ob.value("create_user").toString()
             //       + "','" + dt
                    + "'," + QString::number(ob.value("version").toDouble())
                    + ")";

            if(!qrm->exec(sq)){
                qDebug()<<qrm->lastError().text();
                qDebug()<<qrm->lastQuery();
                QMessageBox::warning(this, "注意","数据表 com_dict_new 插入错误！");
                lastPage = true;
                return false;
            }
            st++;
        }
    }
    return true;
}


bool Form_jcmlxz::putBaseIn( QJsonObject &in, QString code)
{

    currentMsgid = pub::getYbStrJ(code,"");   //
    if(currentMsgid.isEmpty()){
        QThread::msleep(1000);
        currentMsgid = pub::getYbStrJ(code, "");   //
            if(currentMsgid.isEmpty()){
                QMessageBox::information(this,"note",  code + " 申请交易流水号失败！");
            return false; //未能成功申请交易流水号
        }
    }


    in.insert("infno", code);
    in.insert( "msgid", currentMsgid);
    in.insert("mdtrtarea_admvs", pub::hos_insuplc);
    //in.insert("insuplc_admdvs", mpPerson["insuplc_admdvs"] );

    in.insert("insuplc_admdvs","210100");
    in.insert("recer_sys_code", "OwnSoft");
    in.insert("dev_no","");
    in.insert("dev_safe_info","");
    in.insert("cainfo", pub::hos_secretcode);
    in.insert("signtype","");
    in.insert("infver", "V1.0");
    in.insert("opter_type", "1");
    in.insert("opter", pub::usr_code);
    in.insert("opter_name", pub::usr_name);
    in.insert("inf_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
    in.insert("fixmedins_code", pub::hos_ybbh);
    in.insert("fixmedins_name", pub::hos_name);
    in.insert("sign_no", pub::sign_no);

    return true;
}

bool Form_jcmlxz::saveFile(QString file_qury_no, QString jydm)
{
    curStatus = "9102 正在保存下载内容。。。";
    QJsonObject in;

    if(!putBaseIn(in, "9102")){
        return false;
    }

    QJsonObject inpu,inpud;

    inpu.insert("file_qury_no",file_qury_no);
    inpu.insert("filename","plc");   //
    inpu.insert("fixmedins_code", pub::hos_ybbh);   //"0"

    inpud.insert("fsDownloadIn",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);

    qDebug()<<jydm +" 交易入参: "<<indoc;

    //保存入参日志
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    QNetworkReply* reply = manager.post(request,indoc.toJson());

    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意", "9102 http 请求状态错误: " + statusCode.toString());
        return false;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意", "9102 : " + reply->errorString());
        return false;
    }

    QByteArray bt = reply->readAll();

    QString flnm = "d:/0down/" + jydm + "-" + QDateTime::currentDateTime().toString("yyyyMMddHHmmss") +  ".zip";

    QFile f(flnm);
    if(!f.open(QIODevice::WriteOnly)){
        QMessageBox::information(this,"note","create file failed.");

        return false;
    }
    f.write(bt);
    f.close();

    if(hasZip){         //zip库存可用
        QString baseDir = "D:/0down/";      //下载路径
        QString dest;                       //目标文件
        //获取压缩包内文件列表
        QStringList contains = JlCompress::getFileList(flnm);

        for (int n = 0; n< contains.length(); n++) {
            //逐个提取压缩包内的文件
            dest = baseDir + contains[n];
            QString ret = JlCompress::extractFile(flnm, contains[n], dest);

            if(ret.isEmpty()){
                //提取失败
                QMessageBox::warning(this, "注意", "压缩文件提取失败！");
                return false;
            }

            if(!validSave(dest)){
                QMessageBox::warning(this, "注意", "文本文件转换保存失败！");
                return false;
            }

            //validSave保存文件时，将转换之后的文件名称附加".txt"
            if(!importData(dest+".txt")){
                return false;
            }
        }
    }

    return true;
}

void Form_jcmlxz::on_pbQuery_clicked()
{
    QString cond = ui->leCondition->text().trimmed();
    if(cond.isEmpty()){
        QMessageBox::information(this,"错误","未指定查询条件！");
        return;
    }

    QString jydm = pub::getStr(ui->cbbList->currentText()," ",1);   //交易代码

//    lastOperDate = qrm->value(1).toDate().toString("yyyy-MM-dd") + " 00:00:00";

    //startDate = ui->dtStart->date().toString("yyyy-MM-dd") + " 00:00:00";

    //查询不限定起始日期
    startDate = "2000-01-01 00:00:00";

    curStatus = "开始执行 " + jydm + " 交易。。。";

    QJsonObject in;

    if(!putBaseIn(in, jydm)){
        return ;
    }

    QJsonObject inpu,inpud;
    if( jydm == "1312" ){

        inpu.insert("hilist_code", cond);//项目代码
        inpu.insert("updt_time", startDate);   //更新时间
        inpu.insert("page_num", 1);    //当前页数
        inpu.insert("page_size", 50);   //本页数据量

        inpu.insert("vali_flag", "1");   //
        inpu.insert("insu_admdvs", pub::hos_insuplc);   //


    }else if( jydm == "1318" ){

        inpu.insert("hilist_code", cond);//项目代码
        inpu.insert("updt_time", startDate);   //更新时间
        inpu.insert("page_num", 1);    //当前页数
        inpu.insert("page_size", 50);   //本页数据量

    }else if(jydm == "1901"){
        inpu.insert("type", cond);
        inpu.insert("admdvs", pub::hos_insuplc);
        inpu.insert("date", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
        inpu.insert("vali_flag", "1");

    }else{
        QMessageBox::information(this,"错误", "不支持交易 " + jydm + " 的查询功能！");
        return;
    }

    inpud.insert("data",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);

    qDebug()<<jydm +" 交易入参: "<<indoc;

    //保存入参日志
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    QNetworkReply* reply = manager.post(request,indoc.toJson());

    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意", jydm + " http 请求状态错误: " + statusCode.toString());
        return ;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",jydm + " : " + reply->errorString());
        return ;
    }

    QByteArray bt = reply->readAll();

    QString t = QString::fromLocal8Bit(bt);

    QJsonParseError json_error;
    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());
        return ;
    }

    QJsonObject jsob = jsdc.object();

    if(jsob.value("infcode").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意", jydm + " 交易失败：" + t );
        return ;
    }

    retObj = jsob.value("output").toObject();

    endrows = retObj.value("endRow").toDouble();
    nowrows = retObj.value("recordCounts").toDouble();

    ui->lwResult->clear();

    if(jydm == "1312"){
        if(jsob.value("output").toObject().isEmpty()){
            lastPage = true;
            QMessageBox::warning(NULL,"注意", jydm + "返回信息为空 ");
            return ;
        }


        int recCount = jsob.value("output").toObject().value("size").toInt();
        if(recCount == 0){
            lastPage = true;
            QMessageBox::warning(NULL,"注意", jydm + " 查询无结果 ");
            return ;
        }
        lastPage = jsob.value("output").toObject().value("lastPage").toBool();
        QJsonArray retData = jsob.value("output").toObject().value("data").toArray();
        while(recCount > 0){
            recCount--;
            QJsonObject ob = retData[recCount].toObject();

            QString result = ob.value("hilist_code").toString();
            result.append("\t");
            result.append(ob.value("hilist_name").toString());
            result.append("\t");
            result.append(ob.value("begndate").toString());
            result.append("\t");
            result.append(ob.value("enddate").toString());
            result.append("\t");
            result.append(ob.value("vali_flag").toString());
            result.append("\t");
            result.append(ob.value("poolarea_no").toString());
            ui->lwResult->addItem(result);
        }
    }else if(jydm == "1318"){
        if(jsob.value("output").toObject().isEmpty()){
            lastPage = true;
            QMessageBox::warning(NULL,"注意", jydm + "返回信息为空 ");
            return ;
        }


        int recCount = jsob.value("output").toObject().value("size").toInt();
        if(recCount == 0){
            lastPage = true;
            QMessageBox::warning(NULL,"注意", jydm + " 查询无结果 ");
            return ;
        }
        lastPage = jsob.value("output").toObject().value("lastPage").toBool();
        QJsonArray retData = jsob.value("output").toObject().value("data").toArray();
        while(recCount > 0){
            recCount--;
            QJsonObject ob = retData[recCount].toObject();

            QString result = ob.value("hilist_code").toString();
            result.append("\t");
            result.append(ob.value("hilist_lmtpric_type").toString());
            result.append("\t");
            result.append(ob.value("overlmt_dspo_way").toString());
            result.append("\t");
            result.append(QString::asprintf("%.2f",ob.value("hilist_pric_uplmt_amt").toDouble()));
            result.append("\t");
            result.append(ob.value("tabname").toString());

            ui->lwResult->addItem(result);
        }
    }else if(jydm == "1901"){

        if(jsob.value("output").toObject().isEmpty()){
            lastPage = true;
            QMessageBox::warning(NULL,"注意", jydm + "返回信息为空 ");
            return ;
        }

        QJsonArray retData = jsob.value("output").toObject().value("list").toArray();

        if(retData.isEmpty()){
            QMessageBox::warning(NULL,"注意", jydm + " 查询无结果。");
            return ;
        }

        QJsonArray::iterator st = retData.begin();
        QJsonArray::iterator ed = retData.end();
        QString dt;
        while( st != ed){
            QJsonObject ob = st->toObject();
            QString result = ob.value("type").toString();
            result.append("\t");
            result.append(ob.value("label").toString());
            result.append("\t");
            result.append(ob.value("value").toString());
            result.append("\t");
            result.append(ob.value("parent_value").toString());
            result.append("\t");
            result.append(ob.value("sort").toString());
            result.append("\t");
            result.append(ob.value("version").toString());

            ui->lwResult->addItem(result);

            st++;
        }
    }
    ui->leStatus->setText("操作完成");
}

bool Form_jcmlxz::validSave( QString fileName )
{
    //打开指定文本文件，过滤特殊字符 "\", 然后写入新的文件
    QFile sour(fileName);
    QFile dest(fileName + ".txt");

    if(!sour.exists()){
        QMessageBox::warning(NULL,"注意", " 源文件不存在！");
        return false;
    }

    if(dest.exists()){
        if(!dest.remove()){
            QMessageBox::warning(NULL,"注意", " 目标文件存在且无法删除。");
            return false;
        }
    }

    //读取源文件
    sour.open(QFile::ReadOnly);
    QByteArray ar = sour.readAll();
    sour.close();

    //过滤特殊字符
    for(int n = 0; n<ar.length(); n++){
        if(ar[n] == '\\'){
            ar[n] = '/';
        }
        if(ar[n] == '\''){
            ar[n] = ',';
        }
        if(ar[n] == '`'){
            ar[n] = ',';
        }
    }

    //打开目标文件准备写入
    dest.open(QFile::WriteOnly);
    int wrt = dest.write(ar);
    dest.close();
    if( wrt == -1){
        //写入失败
        return false;
    }else{
        //写入成功
        return true;
    }

}

QString Form_jcmlxz::removeSpecialChar(QString s)
{

    s.replace("\\","/");
    s.replace("'","\\'");
//    s.replace("(","\\('");
//    s.replace(")","\\)'");

    return s;
}

void Form_jcmlxz::on_pbSimple_clicked()
{
    ui->pbSimple->setEnabled(false);
    ui->pbExit->setEnabled(false);
    ui->pbQuery->setEnabled(false);
    ui->pbImport->setEnabled(false);
    ui->pbDownload->setEnabled(false);
    qApp->processEvents();  //刷新显示

    //sqlThread * t = new sqlThread(this);
    //t->start();

    tm0->start(390);
    QString jydm = pub::getStr(ui->cbbList->currentText()," ",1);
    if(jydm == "1301_simple"){

    }else if(jydm == "1306_simple"){


    }else{
        QMessageBox::warning(NULL,"注意", " 指定的交易编号没有相关simple表操作。");

    }
    curBusiness = jydm;
    sqlThread * t = new sqlThread(this);
    connect(t,SIGNAL(statusChange(QString)),this,SLOT(threadStatusChange(QString)));
    t->start();

}

void Form_jcmlxz::onSqlFinished()
{

}

void sqlThread::run()
{

    QSqlQuery * qrm0 = new QSqlQuery(pub::db_m);
    QString sq;

    if( curBusiness == "1301_simple"){

        emit statusChange("删除旧数据。。。");
        sq = "drop table new_down_1301_simple";
        qrm0->exec(sq);

        emit statusChange( "正在生成新数据。。。" );
        sq = "create table new_down_1301_simple as select 医疗目录编码,注册名称,批准文号,生产企业名称,药品规格,最小包装数量,最小包装单位 from new_down_1301";
        qrm0->exec(sq);

        emit statusChange( "为新数据建立索引。。。" );
        sq = "ALTER TABLE new_down_1301_simple ADD PRIMARY KEY (`医疗目录编码`), ADD INDEX `index2` (`注册名称` ASC), ADD INDEX `index3` (`批准文号` ASC)";
        qrm0->exec(sq);
    }else if( curBusiness == "1306_simple"){

        emit statusChange("删除旧数据。。。");
        sq = "drop table new_down_1306_simple";
        qrm0->exec(sq);

        emit statusChange( "正在生成新数据。。。" );
        sq = "create table new_down_1306_simple as select 医疗目录编码,耗材名称,规格,注册备案号,生产企业名称,耗材分类 from  new_down_1306";
        qrm0->exec(sq);

        emit statusChange( "为新数据建立索引。。。" );
        sq = "ALTER TABLE new_down_1306_simple ADD PRIMARY KEY (`医疗目录编码`), ADD INDEX `index2` (`耗材名称` ASC), ADD INDEX `index3` (`注册备案号` ASC)";
        qrm0->exec(sq);

    }

    emit statusChange( "stop" );

    currentThread()->exit(0);
}

void Form_jcmlxz::onTime0Out()
{

    //控制状态栏文本闪动显示，当前状态为空则显示状态，状态非空则清空
    if(ui->leStatus->text().isEmpty()){
        ui->leStatus->setText( curStatus );
    }else{
        ui->leStatus->setText("");
    }

}

void Form_jcmlxz::threadStatusChange(QString s)
{
    qDebug() << "threadStatusChange : " << s;
    curStatus = s;
    if(s == "stop"){    //thread is finished
        tm0->stop();
        //curStatus = "操作完成";
        //tm->stop();
        ui->pbSimple->setEnabled(true);
        ui->pbExit->setEnabled(true);
        ui->pbQuery->setEnabled(true);
        ui->pbImport->setEnabled(true);
        ui->pbDownload->setEnabled(true);
        ui->leStatus->setText(  "操作完成" );
    }

}
sqlThread::sqlThread(QWidget * receiver)
{

}
sqlThread::~sqlThread()
{

}
